package cn.campsg.messageboard.controller.Admin;

import cn.campsg.messageboard.utils.DBUtil; // 导入工具类
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.*;

@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 使用try-with-resources确保资源关闭
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ? AND role = 2";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, username);
                stmt.setString(2, password);

                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        HttpSession session = request.getSession();
                        session.setAttribute("admin", username);
                        // 登录成功后跳转Servlet（不是JSP）
                        response.sendRedirect("admin/dashboard");
                    } else {
                        request.setAttribute("error", "用户名或密码错误");
                        request.getRequestDispatcher("admin_login.jsp").forward(request, response);
                    }
                }
            }
        } catch (SQLException e) {
            // 更详细的错误处理
            log("数据库错误: " + e.getMessage(), e);
            request.setAttribute("error", "数据库连接错误，请稍后再试");
            //request.getRequestDispatcher("admin_login.jsp").forward(request, response);
            response.sendRedirect("admin/dashboard");
        }
    }
}